package com.zhanglong.kotlinfish.Util.Web

import android.webkit.JavascriptInterface
import android.webkit.WebView

class JSBridgeUtil constructor (val webView:WebView, var callBack: JSBridgeCallBack) {

    interface JSBridgeCallBack {
        fun jsHandle(cmd: String, param: String, ext: String)
    }

    init {
        webView.addJavascriptInterface(AndroidToJs(), "android")
    }

    private fun evaluateScriptJS(javascript: String) {
        this.webView.post {
            val script = String.format("setTimeout(%s, 1);", javascript)
            webView.evaluateJavascript(script) { }
        }
    }

    private fun evaluateJS(func: String, cmd: String, param: String, ext: String) {
        this.webView.post {
            val script = String.format("setTimeout(function(){%s('%s','%s','%s');}, 1);", func, cmd, param, ext)
            webView.evaluateJavascript(script) { }
        }
    }

    fun evaluateJS(cmd: String, param: String, ext: String) {
        evaluateJS("onRecvNative", cmd, param, ext)
    }

    inner class AndroidToJs : Any() {
        @JavascriptInterface
        fun callNative(cmd: String, param: String, ext: String) {
            callBack.jsHandle(cmd, param, ext)
        }
    }
}